<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getPage">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="shops" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="80">
			</el-table-column>
			<el-table-column prop="name" label="门店名称" width="120" sortable>
			</el-table-column>
			<el-table-column prop="tel" label="电话" width="140" sortable>
			</el-table-column>
			<el-table-column prop="registerTime" label="入驻日期" width="140" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态" width="120" sortable>
				<template scope="scope">
					<span style="color: green" v-if="scope.row.state == 0">审核通过</span>
					<span style="color: red" v-else-if="scope.row.state == 0">审核失败</span>
					<span style="color: gold" v-else>待审核</span>
				</template>
			</el-table-column>
			<el-table-column prop="address" label="地址" width="140" sortable>
			</el-table-column>
			<el-table-column prop="logo" label="图案" width="120" sortable>
			</el-table-column>
			<el-table-column prop="admin_id" label="管理员" width="120" sortable>
			</el-table-column>

			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">审核通过</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">禁用</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next"
						   @current-change="handleCurrentChange"
						   :page-size="pageSize"
						   :total="total"
						   :current-page="page"
						   style="float:right;">
			</el-pagination>
		</el-col>

		<!--
			新增或编辑界面
			:rules：声明校验规则
			ref：绑定当前表单，并给它取一个别名
		-->
		<el-dialog title="新增/编辑" :visible.sync="shopFormVisible" :close-on-click-modal="false">
			<el-form :model="shopForm" label-width="80px" :rules="shopFormRules" ref="shopForm">

				<el-form-item label="姓名" prop="username">
					<el-input v-model="shopForm.username" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="shopForm.email" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="电话" prop="phone">
					<el-input v-model="shopForm.phone" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="年龄" prop="age">
					<el-input v-model="shopForm.age" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="shopForm.state">
						<el-radio class="radio" :label="0">审核通过</el-radio>
						<el-radio class="radio" :label="1">审核失败</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="管理部门" prop="department_id">
					<el-input v-model="shopForm.department_id" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="登录信息" prop="logininfo_id">
					<el-input v-model="shopForm.logininfo_id" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="店铺" prop="shop_id">
					<el-input v-model="shopForm.shop_id" auto-complete="off"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="shopFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="save" :loading="shopLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>

	export default {
		data() {
			return {
				filters: {
					keyword: ''
				},
				shops: [],
				total: 0,
				page: 1,
				pageSize: 10,
				listLoading: false,
				sels: [],//列表选中行

				shopFormVisible: false, //新增或编辑界面是否显示
				shopLoading: false,		// 忙等框是否显示
				shopFormRules: {		// 声明校验规则
					username: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					],
                    email: [
                        { required: true, message: '请输入邮箱', trigger: 'blur' }
                    ],
                    phone: [
                        { required: true, message: '请输入电话', trigger: 'blur' }
                    ],
                    age: [
                        { required: true, message: '请输入年龄', trigger: 'blur' }
                    ]
				},
				//编辑界面数据
				shopForm: {
					id: null,
                    name: '',
                    tel:'',
                    registerTime:null,
					state: 0,
                    address:'',
                    logo:'',
                    admin_id: null
				},
				// shops:[],
                deptTree:[]
			}
		},
		methods: {
			//性别显示转换
			formatSex: function (row, column) {
				return row.state == 0 ? '正常' : row.state == -1 ? '禁用' : '未知';
			},
			handleCurrentChange(val) {
				this.page = val;
				this.getShops();
			},
            // 高级查询每次定位到第一页
            getPage(){
                this.page = 1;
                this.getShops();
            },
			//获取店铺列表
			getShops() {
				let para = {
					currentPage: this.page,
                    pageSize: this.pageSize,
                    keyword: this.filters.keyword
				};
				this.listLoading = true;	// 开启忙等框
				// 发送axios请求，从后端拿数据
				this.$http.post("/shop",para)
					.then(result=>{
                        this.total = result.data.total;
                        this.shops = result.data.rows;
                        this.listLoading = false;
					})
					.catch(result=>{
                        this.$message({
                            message: '系统异常',
                            type: 'error'
                        });
					})
				//NProgress.start();
				/*getShopListPage(para).then((res) => {
					this.total = res.data.total;
					this.shops = res.data.shops;
					this.listLoading = false;
					//NProgress.done();
				});*/
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '温馨提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true; // 开启忙等框
					//NProgress.start();
					this.$http.delete("/shop/"+row.id) // row.id拿到当前店铺的id，传到后台去
						.then(result=>{
                            if(result.data.success){
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                                this.page = 1; // 如果删除成功，跳转到第一页
							}else {
                                this.$message({
                                    message: '删除失败'+result.data.message,
                                    type: 'error'
                                });
							}
                            this.getShops(); // 重新刷新列表
						})
						.catch(result=>{

						})
					/*removeShop(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getShops();
					});*/
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.shopFormVisible = true;	// 显示编辑弹出框
				this.shopForm = Object.assign({}, row);	// 回显数据 ，克隆当前行的数据
                this.getDeptTree(); // 点击新增触发函数，去后台查询店铺树
                // 回显父店铺
                let dirPath = row.dirPath; // /2/5/11
                if(dirPath){
                    let tmp = [];
                    if(dirPath){
                        let dirPaths =  dirPath.trim().split("/"); // ['','2','5','11']
                        // console.log(dirPaths)
                        for(let i=1;i<dirPaths.length-1;i++){
                            tmp[i-1] = parseInt(dirPaths[i]);
                        }
                    }
                    this.shopForm.parent = tmp; //根据dirpath构造数组
                }
			},
			//显示新增界面
			handleAdd: function () {
				this.shopFormVisible = true; // 显示新增弹出框
                this.shopForm = { // 清空表单数据
                    id: null,
                    name: '',
                    tel:'',
                    registerTime:null,
                    state: 0,
                    address:'',
                    logo:'',
                    admin_id: null
                }
                this.getDeptTree(); // 点击新增触发函数，去后台查询店铺树
			},
			//编辑
			save: function () {
				this.$refs.shopForm.validate((valid) => { // 再一次触发表单校验
					if (valid) {
						this.$confirm('确认提交吗？', '温馨提示', {}).then(() => {
							this.shopLoading = true;		// 显示忙等框
							//NProgress.start();
							let para = Object.assign({}, this.shopForm);

                            // 因为这里得到的parent是一个数组，例如：[1,12]，后台parent又是一个对象，因此我们要转换
                            if(para.parent){	// 当父店铺不为空的时候才转换
                                // 从表单中复制对象得到parent
                                let paraArray = para.parent // [1,12]
                                // 将parent数组中的最后一个值拿出来，最后一个值才是我们选中的父店铺
                                let lastParentId = paraArray[paraArray.length-1]
                                // 重新给parent对象赋值，
                                para.parent = {"id":lastParentId};
                            }

							this.$http.put("/shop",para)
								.then(result=>{
                                    this.shopLoading = false;	// 关闭忙等框
									if (result.data.success){
                                        this.$message({
                                            message: "操作成功!",
                                            type: 'success'
                                        });
                                        this.shopFormVisible = false;// 关闭弹出框
                                        this.page = 1; // 定位到第一页
                                        this.getShops(); // 重新刷新列表
									}else {
                                        this.$message({
                                            message: result.data.message,	// 直接提示后端错误
                                            type: 'error'
                                        });
									}
								})
								.catch(result=>{
                                    this.$message({
                                        message: '系统错误',
                                        type: 'error'
                                    });
                                    this.shopLoading = false;		// 关闭忙等框
                                    this.shopFormVisible = false; // 关闭弹出框
								})

							/*shopShop(para).then((res) => {
								this.shopLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['shopForm'].resetFields();
								this.shopFormVisible = false;
								this.getShops();
							});*/
						});
					}
				});
			},

			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id); // [1,2,3]
				this.$confirm('确认删除选中记录吗？', '温馨提示', {
					type: 'warning'
				}).then(() => { // 返回框的确认框
					this.listLoading = true; // 开启忙等框
					//NProgress.start();
					// let para = { ids: ids };
					this.$http.patch("/shop",ids)
						.then(result=>{
							if (result.data.success){ // 删除成功
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
								this.page = 1; // 删除成功，定位到第一页
							}else {
                                this.$message({
                                    message: '删除失败'+result.message,
                                    type: 'error'
                                });
							}
                            this.getShops(); // 重新刷新列表
						})
						.catch(result=>{
                            this.listLoading = false; // 关闭忙等框
                            this.$message({
                                message: '系统异常',
                                type: 'error'
                            });
						})

				}).catch(() => {	// 返回框的取消框

				});
			},
            /*getShops(){
                this.$http.get("/shop")
                    .then(result=>{
                        if (result.data){
                            this.shops = result.data; // result.data 获取店铺的集合
                        }
                    })
            },*/
            /*getDeptTree(){
                this.$http.get("/shop/tree")
                    .then(result=>{
                        if (result.data){
                            this.deptTree = result.data; // result.data 获取店铺树的集合
                        }
                    })
            }*/
		},
		mounted() {
            this.getShops();	// 页面加载就查询店铺的所有数据
		}
	}

</script>

<style scoped>

</style>